/**
 * @Author: colpu
 * @Date: 2025-03-29 19:38:16
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-10-14 16:49:33
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
"use strict";
import assert from "assert";
const MAP = Symbol("Timing#map");
const LIST = Symbol("Timing#list");
import debugFactory from "debug";
const debug = debugFactory("@colpu/core:utils/timing");
class Timing {
  constructor() {
    this[MAP] = new Map();
    this[LIST] = [];
  }

  time(name) {
    if (!name) return;
    if (this[MAP].has(name)) this.timeEnd(name);

    const start = Date.now();
    const item = {
      name,
      start,
      end: undefined,
      duration: undefined,
      pid: process.pid,
      index: this[LIST].length,
    };
    this[MAP].set(name, item);
    this[LIST].push(item);
  }

  timeEnd(name) {
    if (!name) return;
    assert(this[MAP].has(name), `必须先执行 timing.time('${name}')`);
    const item = this[MAP].get(name);
    item.end = Date.now();
    item.duration = item.end - item.start;
    debug(`${name} +%sms`, item.duration);
    return item;
  }
}

export default new Timing();
